package de.zainodis.authorlist.ui;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParserException;

import de.zainodis.commons.LogCat;

import android.os.AsyncTask;

/**
 * 
 * @author zainodis
 * 
 * @param <T>
 *           the target type that is being parsed.
 */
public abstract class XmlDownloadTask<T> extends AsyncTask<Void, Void, Void> {

   @Override
   protected Void doInBackground(Void... args) {
	 try {
	    downloadXml(getUrl());
	 } catch (IOException e) {
	    LogCat.e(getTag(), "Failed to obtain xml document.", e);
	 } catch (XmlPullParserException e) {
	    LogCat.e(getTag(), "Failed to parse xml document.", e);
	 }
	 return null;
   }

   protected void downloadXml(String url) throws XmlPullParserException, IOException {
	 InputStream stream = null;
	 try {
	    stream = getStreamForUrl(url);
	    // Process the downloaded xml
	    parse(stream);

	 } catch (IOException e) {
	    LogCat.e(getTag(), "Failed to obtain xml document.", e);

	 } finally {

	    if (stream != null) {
		  stream.close();
	    }
	 }
   }

   protected InputStream getStreamForUrl(String urlString) throws IOException {
	 URL url = new URL(urlString);

	 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	 // connection.setReadTimeout(10000);
	 // connection.setConnectTimeout(15000);
	 // connection.setRequestMethod("GET");
	 connection.connect();
	 return connection.getInputStream();
   }

   protected abstract void parse(InputStream stream) throws XmlPullParserException, IOException;

   protected abstract String getUrl();

   protected abstract String getTag();
}
